<template>
  <div>
    <a-button @click="openModal" >增加</a-button>
    <a-button @click="deleteId">删除</a-button>
    <a-table 
    :columns="columns" 
    :data-source="dataSource" 
    :row-selection="rowSelection" 
    :row-key="record => record.id"
    :scroll="{ y: 550 }"
    bordered 
    class="editable-table"
    >
      <template #bodyCell="{ column, text, record }">
        <template v-if="['language', 'mathematics', 'english', 'computer'].includes(column.dataIndex)">
          <div class="editable-cell">
            <a-input
              v-if="editableData[record.id]"
              v-model:value="editableData[record.id][column.dataIndex]"
              class="input-cell"
            />
            <template v-else>
              {{ text }}
            </template>
          </div>
        </template>

        <template v-else-if="column.dataIndex === 'operation'">
          <div class="editable-row-operations">
            <span v-if="editableData[record.id]">
              <a-typography-link @click="save(record.id)">保存</a-typography-link>
              <a-popconfirm title="确定取消?" @confirm="cancel(record.id)" okText="确定" cancelText="取消">
                <a>取消</a>
              </a-popconfirm>
            </span>
            <span v-else>
              <a @click="edit(record.id)">编辑</a>
            </span>
          </div>
        </template>
      </template>
    </a-table>
    <StudentScoreAdd :open="isModalOpen" @update:open="isModalOpen = $event" @add="refreshData" />
  </div>
  </template>
  
  <script setup>
  import { cloneDeep } from 'lodash-es';
  import { onMounted, reactive, ref } from 'vue';
  import StudentScoreAdd from '@/components/addStudentScore.vue';
  import { getListStudentScore, updateStudentScore,deleteStudentScore,batchDeleteStudentScore } from '@/api/StudentScoreApi';
  const fetchData = () => {
    getListStudentScore().then(res => {
    dataSource.value = res.data;
  });
};
const refreshData = () => {
  fetchData();
};
const selectedRowKeys=ref([]);
const deleteId = () => {
  const selectedRows = dataSource.value.filter(item => selectedRowKeys.value.includes(item.id));
  console.log('即将删除的行:', selectedRows);

  if (selectedRows.length > 1) {
    // 如果选择的行数大于1，使用批量删除
    const selectedIds = selectedRows.map(item => item.id);
    console.log('批量删除学生成绩 ID:', selectedIds);
    
    // 调用批量删除接口
    batchDeleteStudentScore(selectedIds)
      .then(results => {
        console.log('批量删除成功:', results);
        refreshData(); // 删除后刷新数据
      })
      .catch(error => {
        console.error('批量删除失败:', error);
      });
  } else if (selectedRows.length === 1) {
    // 如果只选择了一行，使用单个删除
    const selectedId = selectedRows[0].id;
    console.log(`正在删除学生成绩 ID: ${selectedId}`);
    
    deleteStudentScore(selectedId)
      .then(results => {
        console.log('删除成功:', results);
        refreshData(); // 删除后刷新数据
      })
      .catch(error => {
        console.error('删除失败:', error);
      });
  } else {
    console.error('没有选择任何行进行删除');
  }
};
const isModalOpen = ref(false);

const openModal = () => {
  isModalOpen.value = true;
};
  onMounted(()=>{
    getListStudentScore().then(res=>{
      dataSource.value=res.data
    })
  })
  const columns = [
    {
      title: '学号',
      dataIndex: 'studentNumber',
      width: '10%',
    },
    {
      title: '语文',
      dataIndex: 'language',
      width: '15%',
    },
    {
      title: '数学',
      dataIndex: 'mathematics',
      width: '15%',
    },
    {
      title: '英语',
      dataIndex: 'english',
      width: '15%',
    },
    {
      title: '计算机',
      dataIndex: 'computer',
      width: '15%',
    },
    {
      title: '操作',
      dataIndex: 'operation',
    },
  ];
  
  const data = [];
  
  const dataSource = ref(data);
  const editableData = reactive({});
  
  const edit = id => {
    editableData[id] = cloneDeep(dataSource.value.find(item => id === item.id));
  };
  
  const save = id => {
  const updatedRecord = Object.assign(dataSource.value.find(item => id === item.id), editableData[id]);
  console.log(updatedRecord);

  // 调用接口更新学生信息
  updateStudentScore(updatedRecord)
    .then(() => {
      delete editableData[id];
      console.log('学生成绩修改成功');
    })
    .catch(error => {
      console.error('学生成绩修改失败:', error);
    });
};
  
  const cancel = id => {
    delete editableData[id];
  };
  const rowSelection = ref({
  onChange: (keys, selectedRows) => {
    selectedRowKeys.value = keys; // 更新选中的行
    console.log(`selectedRowKeys: ${keys}`, 'selectedRows: ', selectedRows);
  },
  getCheckboxProps: record => ({
    disabled: record.name === 'Disabled User',
    name: record.name,
  }),
});

  </script>
  
  <style scoped>
  .editable-row-operations a {
    margin-right: 8px;
  }
  
  .input-cell {
    margin: -5px 0;
  }
  </style>
  